package com.dennytech.tac.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;

import com.dennytech.tac.utils.CFUtils;
import com.dennytech.tac.R;

public class DPTableView extends LinearLayout {

	private Context mContext;
	private int mIndexController = 0;
	private ClickListener mClickListener;

	public DPTableView(Context context, AttributeSet attrs) {
		super(context, attrs);
		mContext = context;
	}

	@Override
	protected void onFinishInflate() {
		super.onFinishInflate();

		build();
	}

	/**
	 * change the default style to table style
	 */
	public void build() {
		if (getChildCount() > 0)
			this.setVisibility(VISIBLE);
		else {
			this.setVisibility(GONE);
			return;
		}

		mIndexController = 0;
		int dip10 = CFUtils.dip2px(mContext, 10);
		if (getChildCount() > 1) {
			for (int i = 0; i < getChildCount(); i++) {
				View tempItemView = getChildAt(i);
				if (mIndexController == 0) {
					tempItemView.setBackgroundResource(R.drawable.background_view_rounded_top);
				} else if (mIndexController == getChildCount() - 1) {
					tempItemView.setBackgroundResource(R.drawable.background_view_rounded_bottom);
				} else {
					tempItemView.setBackgroundResource(R.drawable.background_view_rounded_middle);
				}
				if (tempItemView instanceof DPBasicItem)
					tempItemView.setPadding(dip10, dip10, dip10, dip10);

				if (tempItemView.isClickable()) {
					tempItemView.setTag(mIndexController);
					tempItemView.setOnClickListener(new View.OnClickListener() {

						@Override
						public void onClick(View view) {
							if (mClickListener != null)
								mClickListener.onClick((Integer) view.getTag());
						}

					});
				}
				mIndexController++;
			}
		} else if (getChildCount() == 1) {
			View examView = getChildAt(0);
			examView.setBackgroundResource(R.drawable.background_view_rounded_single);
			if (examView instanceof DPBasicItem)
				examView.setPadding(dip10, dip10, dip10, dip10);

			if (examView.isClickable()) {
				examView.setTag(mIndexController);
				examView.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View view) {
						if (mClickListener != null)
							mClickListener.onClick((Integer) view.getTag());
					}

				});
			}
		}
	}

	@Override
	public void addView(View child) {
		if (child instanceof DPBasicItem)
			((DPBasicItem)child).build();

		super.addView(child);
	}

	public interface ClickListener {
		void onClick(int index);
	}

	public void setClickListener(ClickListener listener) {
		this.mClickListener = listener;
	}

	public void removeClickListener() {
		this.mClickListener = null;
	}

}
